package com.ciitc.zhgl.controller;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ciitc.zhgl.bean.Employee;
import com.ciitc.zhgl.bean.Message;
import com.ciitc.zhgl.myutils.ExcelExportUtil;
import com.ciitc.zhgl.myutils.ExcelImportUtil;
import com.ciitc.zhgl.service.EmployeeService;
import com.ciitc.zhgl.util.DownloadUtils;
import com.ciitc.zhgl.util.ResourceUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 员工处理器
 * @author Administrator
 *
 */
@Controller
public class EmployeeController {
	
	private static final Logger log = LoggerFactory.getLogger(EmployeeController.class);
	
	@Autowired
	EmployeeService employeeService;
	
	@RequestMapping(value="/toImport",method=RequestMethod.GET)
	public String toImport() {
		log.info("跳转到Excel数据导入页面");
		return "importemp";
	}
	
	//@RequestMapping(value="/testimp",method=RequestMethod.POST)
	public String testImport() {
		System.out.println("================aaaaaaa===================");
		return "redirect:/emps";
	}
	
	/**
	 * 导出Excel
	 * @throws Exception 
	 */
	@RequestMapping(value="/export")
	public void exportExcel(HttpServletResponse response) throws Exception {
		
		/*方式一：不基于模板，直接导出*/
		/*
		//获取导出数据
		List<Employee> emps = employeeService.getAll();
		//标题
		String[] titles = "编号,姓名,性别,邮箱,部门编号,部门名称".split(",");
		Workbook wb = ExcelExportUtil.writExcel(titles, emps);
		//下载
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		wb.write(bos);
		bos.close();
		new DownloadUtils().download(bos, response, "员工");
		*/
		
		/*方式二：基于模板导出 主要是获取模板的样式应用于导出文件*/
		//获取导出数据
		List<Employee> emps = employeeService.getAll();
		//因为模板是放在了类路径下  因此可通过封装的工具类获取类路径下的模板文件资源文件流
		FileInputStream in = ResourceUtil.getExcelTemplateStream();
		//通过模板文件流创建工作簿
		Workbook wb = new XSSFWorkbook(in);
		//获取工作簿的Sheet页  目前只考虑第一页有样式
		Sheet sheet = wb.getSheetAt(0);
		//获取Sheet页需要的那一行的每个单元格的样式  根据模板文件的实际情况  此处是第二行
		Row row = sheet.getRow(1);
		//创建一个单元格样式的数组对象  用于存放每个单元格的样式
		CellStyle[] styles = new CellStyle[row.getLastCellNum()];
		for(int cellNum = 0;cellNum<row.getLastCellNum();cellNum++) {
			Cell cell = row.getCell(cellNum);
			styles[cellNum] = cell.getCellStyle();
		}
		
		int rowIndex = 1;
		Cell cell = null;
		for(Employee employee:emps) {
			row = sheet.getRow(rowIndex++);
			cell = row.createCell(0);
			cell.setCellValue(employee.getEmpId());
			cell.setCellStyle(styles[0]);

			cell = row.createCell(1);
			cell.setCellValue(employee.getEmpName());
			cell.setCellStyle(styles[1]);

			cell = row.createCell(2);
			cell.setCellValue(employee.getGender());
			cell.setCellStyle(styles[2]);

			cell = row.createCell(3);
			cell.setCellValue(employee.getEmail());
			cell.setCellStyle(styles[3]);

			cell = row.createCell(4);
			cell.setCellValue(employee.getdId());
			cell.setCellStyle(styles[4]);

			cell = row.createCell(5);
			cell.setCellValue(employee.getDepartment().getDeptName());
			cell.setCellStyle(styles[5]);
		}
		//下载
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		wb.write(bos);
		bos.close();
		new DownloadUtils().download(bos, response, "员工");
	}
	
	/**
	 * 	通过POI导入员工数据
	 * @param file
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value="/empImport",method=RequestMethod.POST)
	public Message importExcel(@RequestParam(name="file")MultipartFile file,HttpServletResponse response) throws Exception {
		log.info("Excel导入开始");
		List<List<Object>> readExcel = ExcelImportUtil.readExcel(file.getInputStream(), file.getOriginalFilename());
		for (List<Object> list : readExcel) {
			Object[] values = new Object[list.size()];
			for(int i = 0;i<list.size();i++) {
				values[i] = list.get(i);
			}
			Employee emp = new Employee(values);
			//保存员工数据
			employeeService.saveEmployee(emp);
		}
		log.info("Excel导入结束");
		return Message.success();
	}
	
	/**
	 *	 根据ID删除信息
	 * @param empId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/deleteemp",method=RequestMethod.POST)
	public Message deleteEmp(String empId) {
		if(empId.contains("-")) {
			String[] ids = empId.split("-");
			for (String string : ids) {
				employeeService.deleteEmp(Integer.parseInt(string));
			}
			return Message.success();
		}else {
			
			Integer id = Integer.parseInt(empId);
			employeeService.deleteEmp(id);
			return Message.success();
		}
	}
	
	/**
	 *	根据员工ID更新员工信息
	 * @param employee
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/updateemp",method=RequestMethod.POST)
	public Message updateEmp(Employee employee) {
		System.out.println(employee);
		employeeService.updateEmp(employee);
		return Message.success();
	}
	
	/**
	 * 	根据员工ID查询员工信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/emp",method=RequestMethod.GET)
	@ResponseBody
	public Message getEmp(@RequestParam("id")Integer id) {
		Employee employee = employeeService.getEmp(id);
		return Message.success().add("emp", employee);
	}
	
	@ResponseBody
	@RequestMapping("/checkuser")
	public Message checkUser(@RequestParam("empName")String empName) {
		//为了和前端正则校验保持一致 先判断用户名是否符正则合校验规则
		String regex = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
		if(!empName.matches(regex)) {
			return Message.fail().add("va_msg", "用户名可以是2-5位中文或者6-16位英文和数字的组合");
		};
		
		boolean b = employeeService.checkUser(empName);
		if(b) {
			return Message.success();
		}else{
			return Message.fail().add("va_msg", "用户名已存在");
		}
	}
	
	/**
	 * 	员工保存 基于reslful
	 *	基于JSR303校验 
	 *	result:绑定JSR303校验的结果
	 * @return
	 */
	@RequestMapping(value="/emp",method=RequestMethod.POST)
	@ResponseBody
	public Message saveEmp(Employee employee,BindingResult result) {
		if(result.hasErrors()) {
			//用于存放错误信息的Map
			Map<String,Object> map = new HashMap<>();
			List<FieldError> fieldErrors = result.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				//错误的属性
				//错误的提示信息
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			return Message.fail().add("errorFields", map);
		}else {
			employeeService.saveEmp(employee);
			return Message.success();
		}
	}
	
	
	/**
	 * 分页查询员工  返回json格式的数据 以便在不同终端进行接收数据
	 * @param pn
	 * @return
	 */
	@RequestMapping("/emps")
	@ResponseBody
	public Message getEmpsWithJson(@RequestParam(value="pn",defaultValue="1")Integer pn) {
		PageHelper.startPage(pn, 5);
		//startPage 方法后的查询自动变为了分页查询
		List<Employee> emps = employeeService.getAll();
		//使用pageInfo包装查询的数据，返回的是一个分页数据包装对象  emps：被包装的数据    5：连续显示的页数
		PageInfo<Employee> page = new PageInfo<>(emps,5);
		return Message.success().add("pageInfo", page);
	}
	
	
	/**
	 * 员工分页查询
	 * 使用pagehelper实现分页查询
	 * @param pn 当前页数
	 * @Model model 使用model对象向页面传递参数
	 * @return
	 */
//	@RequestMapping("/emps")
	public String getEmps(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model) {
		
		/**
		 * 如下使用分页插件 需导入jar包    
		 * 在mybatis配置文件或  spring配置文件中添加插件 
		 * 然后在查询方法之前调用一下语句。传入页码  每页展示数据条数
		 */
		PageHelper.startPage(pn, 5);
		//startPage 方法后的查询自动变为了分页查询
		List<Employee> emps = employeeService.getAll();
		//使用pageInfo包装查询的数据，返回的是一个分页数据包装对象  emps：被包装的数据    5：连续显示的页数
		PageInfo<Employee> page = new PageInfo<>(emps,5);
		model.addAttribute("pageInfo", page);
		return "list";
	}

}
